package com.lagou.nio.buffer;

import java.nio.ByteBuffer;

/**
 * Buffer的添加
 */
public class PutBufferDemo {

    private static void print(ByteBuffer allocate, String msg) {
        System.out.println(msg);
        System.out.println("当前索引所在的位置: " + allocate.position());
        System.out.println("最多能操作索引个数: " + allocate.limit());
        System.out.println("缓冲区的总长度: " + allocate.capacity());
        System.out.println("还能操作的索引个数: " + allocate.remaining());
        System.out.println("是否还能操作缓冲区: " + allocate.hasRemaining());
        System.out.println("==========================");
    }

    public static void main(String[] args) {
        ByteBuffer allocate = ByteBuffer.allocate(10);
        print(allocate, "===创建buffer");

        allocate.position(1);//修改当前索引位置
        allocate.limit(9);   //修改最多能操作到哪个索引位置
        print(allocate, "===修改buffer");

        allocate.put((byte)97);
        print(allocate, "===添加一个字节");

        allocate.put("abc".getBytes());
        print(allocate, "===添加一个数组");

        allocate.put("1234".getBytes());
        print(allocate, "===添加四个字节");

        // 如果缓存区存满后, 可以调整position位置可以重复写,这样会覆盖之前存入索引的对应的值
        allocate.position(0);//修改当前索引位置
        allocate.put("123456789".getBytes());
        print(allocate, "===添加九个字节");

    }

}
